package com.junzhiit.nengji.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.base.spring.Context;
import com.junzhiit.nengji.api.service.UserCouponsService;
import com.junzhiit.nengji.api.web.util.APICodeStatus;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.api.web.vo.UserCouponsVO;
import com.junzhiit.nengji.bo.UserCouponsBO;
import com.junzhiit.nengji.dao.UserCouponsDAO;
import com.junzhiit.nengji.model.UserCoupons;
import com.junzhiit.nengji.model.enums.Status;

@Service
public class UserCouponsServiceImpl  extends Context implements UserCouponsService{

	@Autowired
	private UserCouponsDAO userCouponsDAO;
	
	@Override
	public ResultVO getCoupons(String userId) {
		ResultVO result = new ResultVO();
		List<UserCouponsBO> userCouponsBOList = userCouponsDAO.getCouponsByUserId(userId);
		if(userCouponsBOList.size() == 0){
			result.setStatus(APICodeStatus.USER_COUPONS_IS_EMPTY);
			result.setMessage("member coupons is empty.");
			return result;
		}
		
		List<UserCouponsVO> list = new ArrayList<UserCouponsVO>();
		Date date = new Date();
		for (UserCouponsBO userCouponsBO : userCouponsBOList) {
			UserCouponsVO userCouponsVO = new UserCouponsVO();
			BeanUtils.copyProperties(userCouponsBO, userCouponsVO);
			userCouponsVO.setUserCouponsStatus(Status.ACTIVE.toIntStatus());
			if(userCouponsBO.getEndTime().getTime() <= date.getTime()){
				userCouponsVO.setUserCouponsStatus(Status.INACTIVE.toIntStatus());//优惠券过期
			}
			list.add(userCouponsVO);
		}
		result.setData(list);
		return result;
	}
	
	@Override
	public void handleUserCoupons(Map<String, String> couponsMap) {
		Set<String> set = couponsMap.keySet();
		Iterator<String> iterator = set.iterator();
		List<UserCoupons> userCouponsList = new ArrayList<UserCoupons>();
		while (iterator.hasNext()){
			String ordersId = iterator.next();
			String couponsId = couponsMap.get(ordersId);
			UserCoupons userCoupons = new UserCoupons();
			userCoupons.setId(couponsId);
			userCoupons.setOrderId(ordersId);
			userCoupons.setStatus(Status.INACTIVE.toIntStatus());
			userCouponsList.add(userCoupons);
		}
		if (userCouponsList.size()>0) {
			userCouponsDAO.batchUpdate(userCouponsList);
		}
	}
	
	@Override
	public void handleUserCoupons(String orderNumber,String couponsId) {
		UserCoupons userCoupons = new UserCoupons();
		userCoupons.setId(couponsId);
		userCoupons.setOrderNumber(orderNumber);
		userCoupons.setStatus(Status.INACTIVE.toIntStatus());
		userCouponsDAO.update(userCoupons);
	}
}
